<template>
  <div class="product">
      <!-- 头部区域 --> 
      <el-card class="operate-top-card" >  <!-- shadow="never" -->
          <i class="el-icon-s-order" style="font-size:18px;margin-right:3px"></i>
          <span>商品列表</span> 
          <el-button class="btn-add" type="primary"  size="mini" @click="$router.push('/pm/addProduct')">添加</el-button>
      </el-card>

      <el-card class="operate-top-card" > 
          <i class="el-icon-search" style="font-size:18px;margin-right:3px"></i>
          <span>筛选搜索</span> 
          <el-button class="btn-clear" 
            type="primary"  
            size="mini"
            style="float:right;margin-left:10px;"
            @click="handleResetSearch"
           >清空</el-button>

          <el-button class="btn-find"
            type="primary" 
            size="mini" 
            style="float:right;"
            @click="handleSearchList"
          >查询</el-button>

          <div>
             <el-form 
              ref="productCateForm" 
              :model="listQuery" 
              label-width="200px"
              :inline="true"
              >
          
          <el-form-item label="商品货号">
            <el-input v-model="listQuery.productSn"></el-input>
          </el-form-item>
 
          <el-form-item label="商品分类">
             <el-cascader
                v-model="productCateValue"
                :options="selectProductCateList"
                :props="{ expandTrigger: 'hover' }"
                @change="handleProductCateChange">
              </el-cascader>
          </el-form-item>
          
          <el-form-item label="上架状态">
            <el-select v-model="listQuery.publishStatus" placeholder="请选择上架状态">
             <el-option v-for="item in publishStatusOptions" 
                :key="item.value"
                :label="item.label" 
                :value="item.value"
                >
              </el-option>  
            </el-select>
          </el-form-item>

          <el-form-item label="商品名称:"  >
            <el-input v-model="listQuery.name" style="width:400px"></el-input>
          </el-form-item>
    
        </el-form>
          </div>
       
          <el-table  
            ref = 'multipleSelection'
            :data="listData" 
            v-loading="listLoading" 
            border    
            style="width: 100%" 
            @selection-change="handleSelectionChange"
          >
          <el-table-column
            type="selection" 
            width="55"
            >
          </el-table-column>
            <el-table-column  align="center"   label="编号"  width="80"> 
              <template slot-scope="scope">
                {{scope.$index + 1 + (listQuery.pageNum - 1) * listQuery.pageSize }}
              </template> 
            </el-table-column>
            <el-table-column   align="center"  label="商品图片"  width="160"> 
              <template slot-scope="scope">
                <img style="width:100px;height:100px;"  :src="scope.row.pic" alt=""> 
              </template>
            </el-table-column>
            <el-table-column  prop="name"  align="center"  label="商品名称"  width="250"></el-table-column>
            <el-table-column  align="center"  label="价格/货号" width="150"> 
              <template slot-scope="scope">
                <p>市场价:{{scope.row.originalPrice}}</p>
                <p>商品售价:{{scope.row.price}}</p>
                <p>商品货号:{{scope.row.productSn}}</p>
              </template>
            </el-table-column>
 
             <el-table-column  align="center"  label="操作" width="150"> 
              <template slot-scope="scope">
                <p>上架:
                  <el-switch  
                    v-model="scope.row.publishStatus"
                    :active-value="1"  
                    :inactive-value="0"
                    @change="handlePublishStatusChange(scope.row)"
                    > </el-switch>
                </p>
                <p>新品:
                  <el-switch  v-model="scope.row.newsStatus"
                    :active-value="1"  
                    :inactive-value="0"
                    @change="handleNewsStatusChange(scope.row)"
                    > </el-switch>
                </p>
                 <p>推荐:
                  <el-switch  v-model="scope.row.recommendStatus"
                    :active-value="1"  
                    :inactive-value="0"
                    @change="handleRecommendStatusChange(scope.row)"
                    > </el-switch>
                </p>
                 
              </template>
            </el-table-column>
            <el-table-column  prop="sale" label="销量" align="center" width="150">  
              <template slot-scope="scope">{{scope.row.sale || 0 }}</template>
            </el-table-column>
           
            <el-table-column  prop="store" label="存量" align="center" width="120">  </el-table-column>
             
             <el-table-column   label="操作" align="center"  >
               <template slot-scope="scope">
                  <el-button 
                     size="mini"
                     @click="handleUpdate(scope.row)" 
                  >编辑</el-button>
                  <el-button size="mini" 
                  type="danger"
                  @click="handleDelete(scope.row)" >
                  删除</el-button>
               </template>
            </el-table-column> 
          </el-table>

          <!-- 批量操作列表 -->
          <div class="many-operate-container">
              <el-select  v-model="operatesType"  placeholder="批量操作列表">
                <el-option
                  v-for="item in operates"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" 
                  >
                </el-option>
              </el-select>

               <el-button size="mini" 
                  type="danger"
                  @click="handleManyOperate()" style="margin-left:10px" >
                  确定
                  </el-button>

          </div>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="listQuery.pageNum"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="listQuery.Size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
        </div>
           
      </el-card>

  </div>
</template>

<script>
  import {getProductList,delOneProduct,updateProductWidthList,updateProductWidthListMany,deleteProductWidthListMany} from '@/api/productApi'
  import {getCategoryWithChildren} from '@/api/categoryApi'

  let defaultQuery = {
    productSn: null, // 商品货号
    productCategoryId: null, // 商品分类
    publishStatus: null, // 上架状态
    name:'', // 商品名称  , 
    pageNum:1,
    pageSize:5
  }

export default { 
  data(){
    return {
      listQuery: Object.assign({},defaultQuery),
      listData:[],
      // 分类列表
      selectProductCateList:[],
      productCateValue:[],
      // 商品是否上架
      publishStatusOptions:[
        {value:0,label:'下架'},
        {value:1,label:'上架'}
      ],
      multipleSelection:'',
      // 表格加载动画
      listLoading:false,
      // 总页数
      total: 0,
      // 批量操作的选项
      operates:[
        {
          label:"批量上架",
          value:"publishOn"
        },
        {
          label:"批量下架",
          value:"publishOff"
        }, 
        {
          label:"批量推荐",
          value:"recommendOn"
        }, 
        {
          label:"批量取消推荐",
          value:"recommendOff"
        },
        {
          label:"批量上新",
          value:"newsOn"
        }, 
        {
          label:"批量下新",
          value:"newsOff"
        }, 
        {
          label:"批量删除",
          value:"manyDel"
        }
      ],
      operatesType: ''
    }
  },
  created(){

     // 0 获取分类数据
    this.getCategoryList()
    // 1 获取商品列表
    this.getList()
  },
  methods:{ 
    handleProductCateChange(value) {
      if(value.length == 1){ // 一级
        this.listQuery.productCategoryId = value[0] 
      }else if(value.length == 2){ // 二级
        this.listQuery.productCategoryId = value[1] 
      }else{
        this.listQuery.productCategoryId = null
      }
    }, 

    // 0 获取分类数据
    async getCategoryList(){
      let res = await getCategoryWithChildren() 
      if(res.status === 1){ 
        let listArr = res.data;
        this.productCateOptions = [];
        for(let i=0; i< listArr.length;i++){
          let children = [];
          if(listArr[i].children !=null && listArr[i].children.length > 0){
            for(let j=0;j< listArr[i].children.length;j++){
              children.push({
                value:listArr[i].children[j].id,
                label:listArr[i].children[j].name
              })
            } 
          } 
          children = children.length > 0 ? children : null;
          this.selectProductCateList.push({
              value:listArr[i].id,
              label:listArr[i].name,
              children
          })
        }
      }
      
    },

    // 1 获取商品列表
    async getList(){
      this.listLoading = true
      let res = await getProductList(this.listQuery)
      if(res.status === 1){  
        this.listData = res.data.product_list
        this.total = res.data.product_count
      }else{
        this.$message.error('获取商品列表失败')
      }
      this.listLoading = false 
    },

    // 2  改变每页显示条数
    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      // 重新加载数据
      this.getList();
    },

    // 3 当前页码发生改变
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      // 重新加载数据
      this.getList();
    },

    // 4 删除一个商品
    handleDelete(row){
       this.$confirm('确定要删除该商品吗?','提示',{
        type:'warning'
      }).then(res=>{
        delOneProduct(row.id).then(res=>{
          if(res.status === 1){
            this.$message.success(res.msg)
            // 重新请求数据
            this.getList()
          }else{
            this.$message.error(res.msg)
          } 
        }) 
      }).catch(err=>{
        this.$message.info('已取消删除')
      })
 
    },

    // 5 编辑商品
    handleUpdate(row){
      this.$router.push({
        path:'/pm/updateProduct',
        query:{
          id:row.id
        }
      })
    },

    // 6 商品上架 取消
    handlePublishStatusChange(row){ 
      this.localUpdateProduct({
        id:row.id,
        publishStatus:row.publishStatus
      })
    },

    // 7 是否新品
    handleNewsStatusChange(row){ 
       this.localUpdateProduct({
        id:row.id,
        newsStatus:row.newsStatus
      })
    },

    // 8  是否推荐
    handleRecommendStatusChange(row){ 
       this.localUpdateProduct({
        id:row.id,
        recommendStatus:row.recommendStatus
      })
    },

    // 局部更新列表数据
    async localUpdateProduct(paramObj){
      let res = await updateProductWidthList(paramObj)
      if(res.status === 1){
          this.$message.success(res.msg) 
      }else{
          this.$message.error(res.msg)
      } 
    },

    // 9 根据条件 查询列表 
    handleSearchList(){
      this.listQuery.pageNum = 1
      this.getList()
    },
     
    // 10 清空 查询列表
    handleResetSearch(){
      this.productCateValue = []
      this.listQuery =  Object.assign({},defaultQuery) 
      // this.getList()
    },

    // 11 批量操作
    handleManyOperate(){ 
      // 批量操作的选项
      if(this.operatesType == ''){
         this.$message.warning('请选择批量操作的选项')
         return 
      } 

      // 判断是否有选中的记录
      if(this.multipleSelection.length < 1){
         this.$message.warning('请选择要操作的商品')
         return 
      }

      // 提示用户是否进行批量操作
      this.$confirm('确定要批量操作吗?','提示',{
        type:'warning'
      }).then(() =>{

        // 获取所有id
        let ids = [];
        for(let i=0;i<this.multipleSelection.length;i++){
          ids.push(this.multipleSelection[i].id)
        }

        // console.log(ids);

        switch(this.operatesType){
          case this.operates[0].value:
            this.updatePublishStatus(1,ids);
            break;
          case this.operates[1].value:
            this.updatePublishStatus(0,ids);
            break;
          case this.operates[2].value:
            this.updateRecommendStatus(1,ids);
            break;
          case this.operates[3].value:
            this.updateRecommendStatus(0,ids);
            break;
          case this.operates[4].value:
            this.updateNewsStatus(1,ids);
            break;
          case this.operates[5].value:
            this.updateNewsStatus(0,ids);
            break;
          case this.operates[6].value:
            this.updateDeleteStatus(ids);
            break; 
          default: 
            break; 
        } 
         
      }).catch(err=>{
        this.$message.info('已取消操作')
      })
   
    },

    // 上架和下架
    async updatePublishStatus(status,ids){
        let params = {};
        params.ids = ids;
        params.publishStatus = status
        let res = await updateProductWidthListMany(params);
        if(res.status === 1){
        this.$message.success('修改成功')
          // 重新请求数据
          this.getList()
        }else{
          this.$message.error(res.msg)
        }  
    }, 
    //  推荐 和 取消推荐
    async updateRecommendStatus(status,ids){
       let params = {};
        params.ids = ids;
        params.recommendStatus = status
        let res = await updateProductWidthListMany(params);
        if(res.status === 1){
        this.$message.success('修改成功')
          // 重新请求数据
          this.getList()
        }else{
          this.$message.error(res.msg)
        }  
    }, 

    //  上新 和 取消上新
    async updateNewsStatus(status,ids){
        let params = {};
        params.ids = ids;
        params.newsStatus = status
        let res = await updateProductWidthListMany(params);
        if(res.status === 1){
          this.$message.success('修改成功')
          // 重新请求数据
          this.getList()
        }else{
            this.$message.error(res.msg)
        } 
    },
 
    //  批量 删除
    async updateDeleteStatus(ids){
      let res = await deleteProductWidthListMany(ids)
      if(res.status === 1){
        this.$message.success('批量删除成功')
        // 重新请求数据
        this.getList()
      }else{
        this.$message.error(res.msg)
      } 
    },
 
   // 列表复选框 批量选择
    handleSelectionChange(val){ 
      this.multipleSelection = val 
    } 

  }
}
</script>

<style lang="less" scoped>
.product{
  width: 100%; ; 
}
</style>
